package com.zjhome.cloudnote.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zjhome.cloudnote.constant.ErrorCode;
import com.zjhome.cloudnote.domain.UserInfo;
import com.zjhome.cloudnote.exception.BaseException;
import com.zjhome.cloudnote.param.ModifyPwsdParam;
import com.zjhome.cloudnote.service.UserService;

import io.swagger.annotations.Api;

@RestController
@RequestMapping("/usermgr")
@Api(value = "用户管理")
public class UserController extends BaseController {
	@Autowired
	private UserService		userService;
	
	@PostMapping("/modpswd")
	UserInfo modifyPassword(ModifyPwsdParam modifyPwsdParam) throws Exception {
		String userId = this.getUserId();
		String oldpswd = modifyPwsdParam.getOldpswd();
		
		// 确认密码正确性
		UserInfo userInfo = userService.selectUserById(userId);		
		if (!this.bCryptPasswordEncoder.matches(oldpswd, userInfo.getPassword())) {
			// 旧密码不正确
			logger.warn("旧密码不正确");
			throw new BaseException("", ErrorCode.ERR_OLD_PSWD);
		}
		
		if (!modifyPwsdParam.getAffirm().equals(modifyPwsdParam.getNewpswd())) {
			// 两次输入密码不一致
			logger.warn("两次输入密码不一致");
			throw new BaseException("", ErrorCode.ERR_DIFF_PSWD);
		}
		
		userInfo.setPassword(bCryptPasswordEncoder.encode(modifyPwsdParam.getAffirm()));	// 更新密码
		userService.updateUserByParam(userInfo);
		
		return userInfo;
	}
	
}
